<?php
if (! defined('IN_STUCLOUD')) {
    die('访问受限，禁止直接访问文件');
}
require_once (dirname(__FILE__) . '/Smtp.class.php');
session_start();

/**
 * 用户注册
 *
 * @param string $username
 *            用户名
 * @param string $password
 *            密码
 * @param string $email
 *            邮箱
 * @return boolean 是否注册成功，如果失败一般情况下为email已经存在。
 */
function register($username, $password, $email, $logindirect)
{
    global $_GCONFIG;
    $con = getConnection();
    if (emailExists($email)) {
        return false;
    }
    $pwhash = hash256($password);
    $ip = getIp();
    $verifyhash = hash256(uniqid());
    $isMailVerified = false;
    $sessionid = session_id();
    $sql = "INSERT INTO `userlogin` (`passwordhash`, `registerip`, `lastloginip`, `mail`, `isMailVerified`, `verifyHash`, `sessionid`) VALUES ('$pwhash', '$ip', '$ip', '$email', '$isMailVerified', '$verifyhash','$sessionid')";
    $con->query($sql);
    insertProfile(array(
        "name" => $username
    ));
    insertHomeState();
    if ($logindirect) {
        logout();
        login($password, $email);
        loginSession(toUID($email));
    }
    return true;
}

/**
 * 用户登录
 *
 * @param string $password
 *            密码
 * @param string $uid
 *            uid或mail
 * @return boolean
 */
function login($password, $uid)
{
    $uid = toUID($uid);

    $con = getConnection();
    $pwhash = hash256($password);
    $sql = "SELECT uid FROM `userlogin` WHERE `uid` = '$uid' and `passwordhash`='$pwhash'";
    $con->query($sql);
    if ($con->isEmpty()) {
        return false;
    }
    loginSession($uid);
    return true;
}

/**
 * 查找邮件是否已经被注册
 *
 * @param
 *            $email
 * @return boolean
 */
function emailExists($email)
{
    $con = getConnection();
    $sql = "SELECT uid FROM `userlogin` WHERE `mail` = '$email'";
    $con->query($sql);
    return ! $con->isEmpty();
}

/**
 * 获取用户UID通过EMAIL
 *
 * @param string $email
 *            email
 * @return string 用户UID
 */
function getUIDByEmail($email)
{
    $con = getConnection();
    $con->query("SELECT uid FROM `userlogin` WHERE `mail` = '$email'");
    if ($con->isEmpty()) {
        return false;
    }
    return $con->fetch_assoc()["uid"];
}

/**
 * 用户登出
 *
 * @return boolean
 */
function logout()
{
    if (isLogined()) {
        sessionClose();
        return true;
    }
    return false;
}

function ban($uid, $reasion)
{}

function unban($uid)
{}

/**
 * 从数据库获取用户登录相关的存档
 *
 * @param string $uid
 *            存档
 * @return array
 */
function getLoginInfo($uid)
{
    $con = getConnection();
    $con->query("SELECT * FROM `userlogin` WHERE `uid`='$uid'");
    return $con->fetch_assoc();
}

function insertHomeState()
{
    $con = getConnection();
    $con->query("INSERT INTO `user_home_state` (`active_amount`, `leave_message_amount`) VALUES ('0', '0');");
    return true;
}

/**
 * 从数据库获取用户信息相关的存档
 *
 * @param string $uid
 *            存档
 * @return array
 */
function getProfile($uid)
{
    $con = getConnection();
    $con->query("SELECT * FROM `userprofile` WHERE `uid`='$uid'");
    $profile = $con->fetch_assoc();
    if(empty($profile)){
        return $profile;
    }
    if ($profile["hasimage"]) {
        $uid = $profile["uid"];
        $profile["image"] = "/user/$uid.png";
    } else {
        $profile["image"] = "/image/testhead.png";
    }
    return $profile;
}

/**
 * 从数据库获取用户admin权限列表
 *
 * @param string $uid
 *            存档
 * @return array
 */
function getAdminPermissions($uid)
{
    $con = getConnection();

    $con->query("SELECT * FROM `admin_permissions` WHERE `uid`='$uid'");
    return $con->fetch_assoc();
}

/**
 * 更新登录信息（最后登录IP等）
 *
 * @param string $uid
 */
function updateUserLoginInfo($uid)
{
    $con = getConnection();
    $sessionid = session_id();
    $ip = getIp();
    $con->query("UPDATE `userlogin` SET `lastloginip`='$ip',`lastlogintime`=NOW(),`sessionid`='$sessionid' WHERE `uid`='$uid'");
}

/**
 * 获取用户储存在数据表中的sessionid
 *
 * @param
 *            string uid;
 * @return mixed
 */
function getSessionID($uid)
{
    $uid = toUID($uid);
    $con = getConnection();
    $con->query("SELECT sessionid FROM `userlogin` WHERE `uid`='$uid'");
    return $con->fetch_assoc()["sessionid"];
}

/**
 * 将可能的mail转换成UID模式。
 * 如果mail不存在或者来源为UID则返回自身。
 *
 * @param
 *            $id
 * @return boolean
 */
function toUID($id)
{
    $uid = getUIDByEmail($id);
    if ($uid) {
        return $uid;
    } else {
        return $id;
    }
}

/**
 * 登录会话
 *
 * @param string $uid
 *            uniqueid（或者邮箱）
 */
function loginSession($uid)
{
    $uid = toUID($uid);
    updateUserLoginInfo($uid);
    sessionStart(getLoginInfo($uid), getProfile($uid), getAdminPermissions($uid));
}

/**
 * 验证用户
 *
 * @param string $verifyHash
 *            验证hash
 * @return boolean 是否成功
 */
function verifyStudent($verifyHash)
{
    $con = getConnection();
    $con->query("SELECT uid FROM `userlogin` WHERE `verifyHash`='$verifyHash' AND isMailVerified=0;");
    if (! $con->isEmpty()) {
        $con->query("UPDATE `userlogin` SET `isMailVerified`='1' WHERE `verifyHash` = '$verifyHash'");
        global $_G;
        $_G["logininfo"]["isMailVerified"] = 1;
        $_SESSION["logininfo"]["isMailVerified"] = 1;
        return true;
    }
    return false;
}

function setVerifyState($u, $state)
{
    $uid = toUID($u);
    $con = getConnection();
    $con->query("UPDATE `userlogin` SET `isMailVerified`='$state' WHERE `uid` = '$uid'");
}

function updateVerifyHash($id)
{
    $uid = toUID($id);
    $verifyhash = hash256(uniqid());
    $con = getConnection();
    $con->query("UPDATE `userlogin` SET `verifyHash`='$verifyhash' WHERE `uid` = '$uid'");
    return $verifyhash;
}

function isVerified()
{
    global $_G;
    $con = getConnection();
    $uid = $_G["logininfo"]["uid"];
    $con->query("SELECT uid FROM `userlogin` WHERE `uid`='$uid' AND isMailVerified=0;");
    return $con->isEmpty();
}

/**
 * 发送验证邮件
 *
 * @param string $username
 *            用户名
 * @param string $mailto
 *            邮箱地址
 * @param string $verifyHash
 *            验证hash
 * @return boolean 是否成功
 */
function sendVerifyMail($username, $mailto)
{
    global $_GCONFIG;
    $verifyHash = updateVerifyHash($mailto);
    if ($verifyHash == "") {
        return false;
    }
    $mailsubject = "=?UTF-8?B?" . base64_encode($_GCONFIG["smtp"]["subject"]) . "?=";
    $mb = str_replace("{studentName}", $username, $_GCONFIG["smtp"]["body"]);
    $mb = str_replace("{verifyHash}", $verifyHash, $mb);
    $mb = str_replace("{time}", date("Y-m-d", time()), $mb);
    $mailbody = $mb;
    $smtp = new smtp($_GCONFIG["smtp"]["server"], $_GCONFIG["smtp"]["port"], true, $_GCONFIG["smtp"]["user"], $_GCONFIG["smtp"]["passwd"]);
    $smtp->debug = false;
    $state = $smtp->sendmail($mailto, $_GCONFIG["smtp"]["user"], $mailsubject, $mailbody, "HTML");
    return $state != "";
}

/**
 * 启动会话
 *
 * @param array $profile
 *            用户存档
 */
function sessionStart($logininfo = array(), $profile = array(), $admininfo = array())
{
    session_unset();
    $_SESSION["isLogined"] = true;
    $_SESSION["logininfo"] = $logininfo;
    $_SESSION["profile"] = $profile;
    $_SESSION["admininfo"] = $admininfo;
}

/**
 * 关闭会话，退出登录
 */
function sessionClose()
{
    $_SESSION = array();
    if (isset($_COOKIE[session_name()])) {
        setcookie(session_name(), '', time() - 3600, '/');
    }
    session_destroy();
}

/**
 * 用户是否登录了
 *
 * @return boolean 是否登录
 */
function isLogined()
{
    return isset($_SESSION["isLogined"]);
}

/**
 * 更改密码
 *
 * @param string $uid
 * @param string $password
 */
function chengePassword($uid, $password)
{
    $uid = toUID($uid);
    $con = getConnection();
    $sessid = getSessionID($uid);
    removeSessionFile($sessid);
    $password = hash256($password);
    $con->query("UPDATE `userlogin` SET `passwordhash`='$password',`sessionid`='unset' WHERE `uid`='$uid'");
}

/**
 * 删除会话文件
 *
 * @param string $sessionid
 * @return boolean
 */
function removeSessionFile($sessionid)
{
    $filename = session_save_path() . "/sess_" . $sessionid;
    return unlink($filename);
}

/**
 * 更新用户存档
 */
function dealG()
{
    global $_G;
    $_G["logininfo"] = $_SESSION["logininfo"];
    $_G["profile"] = $_SESSION["profile"];
    $_G["admininfo"] = $_SESSION["admininfo"];
}

function insertProfile($profile)
{
    global $_GCONFIG;
    foreach ($_GCONFIG["user"]["profile"] as $key => $value) {
        if (! isset($profile[$key])) {
            $profile[$key] = $value;
        }
    }
    $gender = $profile["gender"];
    $birthday = $profile["birthday"];
    $joinschooldate = $profile["joinschooldate"];
    $introduction = $profile["introduction"];
    $hasimage = $profile["hasimage"];
    $grade = $profile["grade"];
    $class = $profile["class"];
    $name = $profile["name"];
    $con = getConnection();
    $con->query("INSERT INTO `userprofile` (`name`, `gender`, `birthday`, `joinschooldate`, `introduction`, `hasimage`, `grade`, `class`) VALUES ('$name', '$gender', '$birthday', '$joinschooldate', '$introduction', '$hasimage', '$grade', '$class')");
}

function updateProfile($uid, $profile)
{
    global $_GCONFIG;
    foreach ($_GCONFIG["user"]["profile"] as $key => $value) {
        if (! isset($profile[$key])) {
            $profile[$key] = $value;
        }
    }
    $gender = $profile["gender"];
    $birthday = $profile["birthday"];
    $joinschooldate = $profile["joinschooldate"];
    $introduction = $profile["introduction"];
    $hasimage = $profile["hasimage"];
    $grade = $profile["grade"];
    $class = $profile["class"];
    $name = $profile["name"];
    $con = getConnection();
    $con->query("UPDATE `userprofile` SET `name` = '$name', `gender` = '$grade', `birthday` = '$birthday', `joinschooldate` = '$joinschooldate', `introduction` = '$introduction', `hasimage` = '$hasimage', `grade` = '$grade', `class` = '$class' WHERE `userprofile`.`uid` = $uid");
}
?>